package cn.edu.hqu.cst.android.client_1;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.et_main_content) EditText et_main_content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        new Thread(new ClientThread()).start();
    }
    @OnClick(R.id.btn_main_send)
    void send(){
        Message msg=new Message();
        msg.what=0x1234;
        Bundle bundle =new Bundle();
        bundle.putString("sendContent",et_main_content.getText().toString());
        msg.setData(bundle);
        ClientThread.sendHandler.sendMessage(msg);

    }
}

class ClientThread implements  Runnable{
    DatagramSocket remoteDs=null;
    InetAddress remoteAddr=null;
    private final static int remotePort=5000;
    byte[] buf=new byte[1024];
    public static Handler sendHandler;
    public ClientThread(){
        try {
            remoteDs=new DatagramSocket();
            remoteAddr= InetAddress.getByName("127.0.0.1");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        new Thread(){
            @SuppressLint("HandlerLeak")
            @Override
            public void run() {
                Looper.prepare();
                sendHandler=new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        if(msg.what==0x1234){
                            byte[] buffer=msg.getData().getString("sendContent").getBytes();
                            DatagramPacket remoteDp=new DatagramPacket(buffer,buffer.length,remoteAddr,remotePort);
                            try {
                                remoteDs.send(remoteDp);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                Looper.loop();

            }
        }.start();
    }
}